function ns = orderapp(n,nd)
%
% NS = ORDERAPP(N,ND)  Visualization-oriented approximation
% Let N be a number and ND an interger number. The output NS is the
% ND digits approximation of N with the constrain that, if N > 1, no
% decimal digits are shown.
% The NS class is char.
% This function acts on scalar variables only. If the input variable
% is an array, the function operates on N(1) and a warning message is
% also shown.
% If N is not a number, the string 'NaN' is returned.
%
% Examples:
%
%   orderapp(5234.4,1) returns 5000 
%   orderapp(5234.4,2) returns 5200
%   orderapp(5234.4,8) returns 5234
%   orderapp(0.0347,1) returns 0.03
%   orderapp(0.0347,9) returns 0.0347 
%
% If ND is empty or undefined, ND = 1 is assumed.

% G. Teza, 2012

if nargin < 2 || isempty(nd), nd = 1; end
if isempty(n) || iscell(n), ns = 'NaN'; return; end 
if numel(n) > 1
    n = n(1); 
    disp('Warning: orderapp acts on n(1) only');
end
if isinf(n) || isnan(n), ns = num2str(n); return; end
if ~isnumeric(n), ns = 'NaN'; return; end

ns = num2str(n);
ls = numel(ns);

if strcmp(ns(1),'0')  % case n < 0
    Inzp = zeros(ls,1);
    for k = 1:ls
        Inzp(k) = strcmp(ns(k),'0') || strcmp(ns(k),'.'); 
    end
    kmin = find(~Inzp,1);
    if ~isempty(kmin)
        if kmin+nd <= ls
            ns(kmin+nd:end) = [];
        end
    else
        ns = '0';
    end
else               % case n > 0
    Ip = zeros(ls,1);
    for k = 1:ls
        Ip(k) = strcmp(ns(k),'.');
    end
    k0 = find(Ip,1);
    if ~isempty(k0)      % case without decimal point  
        if k0 > nd+1     % in this case, the round part must be reduced
            ns(nd+1:k0-1) = num2str(zeros(k0-nd-1,1));
        end
        ns(k0:end) = [];
    else
        ns(nd+1:end) = num2str(zeros(ls-nd,1));
    end
end